package whu.cn.whushare.common;

import android.content.Context;
import android.content.SharedPreferences;

import com.androidplus.util.StringUtil;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import whu.cn.whushare.ui.setting.SettingStatistics;

import whu.cn.whushare.bean.User;
import whu.cn.whushare.util.GsonUtil;

/**
 * 类 名：SPManager
 * 功 能：管理用户设置数据
 *       主要包括对用户信息的操作、对用户设置数据的操作和对用户历史数据信息的操作
 */
public class SPManager {
	private static final String CONTEXT = "common";
	private static final String USER_INFO = "user_infos";
	private static final String SETTING_STATISTICS_INFO = "setting_statistics";
	private static final String SETTING_STATISTICS_LAST_UPDATE_TIME = "setting_statistics_last_update_time";
	private static final String APP_SETTINGS = "app_settings";
	private static final String SEARCH_HISTORY = "search_history";
	private static final int SEARCH_HIS_MAX_NUM = 128;

	private Context mContext;
	private static SPManager INSTANCE;
	private SharedPreferences mSP;
	private SharedPreferences.Editor mEditor;
	private Set<String> mSearchHisSet;

	private SPManager(Context context) {
		mContext = context.getApplicationContext();
		mSP = context.getSharedPreferences(CONTEXT, Context.MODE_PRIVATE);
		mEditor = mSP.edit();
        mEditor.apply();
		mSearchHisSet = getSearchHistory();
	}

    //获取SPManager全局实例对象
	public synchronized static SPManager getInstance(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new SPManager(context);
		}
		return INSTANCE;
	}

    //将用户信息保存为json字符串
	public void saveUserInfo(User user) {
		mEditor.putString(USER_INFO, GsonUtil.toJson(user, new TypeToken<User>() {
		}.getType())).commit();
	}

    //删除用户信息
	public void removeUserInfo() {
		mEditor.remove(USER_INFO).commit();
	}

    //获取用户信息
	public String getUserInfo() {
		return mSP.getString(USER_INFO, null);
	}

    //将用户设置数据信息保存为json字符串
	public void saveSettingStatisticsInfo(SettingStatistics stat) {
		if (stat == null) {
			mEditor.remove(SETTING_STATISTICS_INFO).commit();
		} else {
			mEditor.putString(SETTING_STATISTICS_INFO, GsonUtil.toJson(stat, new TypeToken<SettingStatistics>() {
			}.getType())).commit();
		}
	}

    //获取用户设置数据信息
	public SettingStatistics getSettingStatisticsInfo() {
		String string = mSP.getString(SETTING_STATISTICS_INFO, null);
		if (StringUtil.isNullOrEmpty(string)) {
			return new SettingStatistics();
		} else {
			return GsonUtil.fromJsonSimple(string, new TypeToken<SettingStatistics>() {
			}.getType());
		}
	}

    //获取最近设置数据更新时间
	public long getLastSettingStatUpdateTime() {
		return mSP.getLong(SETTING_STATISTICS_LAST_UPDATE_TIME, 0);
	}

    //保存最近设置数据更新时间
	public void saveLastSettingStatUpdateTime(long time) {
		mEditor.putLong(SETTING_STATISTICS_LAST_UPDATE_TIME, time).commit();
	}

    //获取APP设置信息
	public int getAppSettings() {
		return mSP.getInt(APP_SETTINGS, 0);
	}

    //保存APP设置信息
	public void saveAppSettings(int i) {
		mEditor.putInt(APP_SETTINGS, i).commit();
	}

    //保存用户搜索历史集
	public void saveSearchHistories(Set<String> his) {
		mSearchHisSet = his;
		mEditor.putStringSet(SEARCH_HISTORY, mSearchHisSet).commit();
	}

    //保存单条搜索历史信息
	public void saveSearchHistory(String his) {

		if (mSearchHisSet.size() < SEARCH_HIS_MAX_NUM) {
			mSearchHisSet.add(his);
		} else {
            //当历史信息集合超出最大长度时，将数据集减半，只保留最近的半部分历史信息（>>1右移一位）
			List<String> list = new ArrayList<>(mSearchHisSet).subList(SEARCH_HIS_MAX_NUM >> 1, SEARCH_HIS_MAX_NUM);
			mSearchHisSet = new HashSet<>(list);
			mSearchHisSet.add(his);
		}
		mEditor.putStringSet(SEARCH_HISTORY, mSearchHisSet).commit();
	}

    /**
     * 删除指定搜索历史信息
     * @param str - 待删除的搜索历史信息
     */
	public void removeSearchHistory(String str) {
		mSearchHisSet.remove(str);
		mEditor.putStringSet(SEARCH_HISTORY, mSearchHisSet).commit();
	}

    //获取搜索历史集
	public Set<String> getSearchHistory() {
		return mSP.getStringSet(SEARCH_HISTORY, new HashSet<String>());
	}
}
